package encoding

import (
	"gameServer/encoding/json"
	"gameServer/encoding/msgpack"
	"gameServer/encoding/proto"
	"gameServer/encoding/toml"
	"gameServer/encoding/xml"
	"gameServer/encoding/yaml"
	"gameServer/log"
)

var codecs = make(map[string]Codec)

func init() {
	// 把默认的这些编码器都注册进去
	RegisterCodec(json.DefaultCodec)
	RegisterCodec(proto.DefaultCodec)
	RegisterCodec(toml.DefaultCodec)
	RegisterCodec(xml.DefaultCodec)
	RegisterCodec(yaml.DefaultCodec)
	RegisterCodec(msgpack.DefaultCodec)
}

type Codec interface {
	// 编码器类型
	Name() string
	// Marshal 编码
	Marshal(v interface{}) ([]byte, error)
	// 解码
	Unmarshal(data []byte, v interface{}) error
}

// 注册编码器这块，有点和前面的内容相似了，只不过没那么复杂，有时候还是从简好，，，

// 注册编码器
func RegisterCodec(codec Codec) {
	if codec == nil {
		log.Fatal("register codec: codec is nil")
	}
	name := codec.Name()

	if name == "" {
		log.Fatal("register codec: codec without name")
	}
	if _, ok := codecs[name]; ok {
		log.Warnf("the old %s codec will be overwritten", name)
	}

	codecs[name] = codec
}

// 调用编码器
func InvokeCodec(name string) Codec {
	codec, ok := codecs[name]
	if !ok {
		log.Fatalf("%s codec is not registered", name)
	}
	return codec
}
